<template>
  <div class="container">
    <div class="top">
      <el-date-picker
        value-format="yyyy-MM-dd"
        v-model="date"
        type="daterange"
        :clearable="false"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
      <el-select
        v-model="search.area"
        filterable
        remote
        center
        reserve-keyword
        placeholder="请输入区域"
        :remote-method="insideRemoteMethods"
        :loading="insideArea.loading"
      >
        <el-option
          v-for="item in insideArea.options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-input
        style="width: 200px; margin-bottom: 5px"
        v-model="search.bank_name"
        clearable
        placeholder="请输入付款单号"
      >
      </el-input>
      <el-button
        size="small"
        type="primary"
        class="handleSearch"
        icon="el-icon-search"
        @click="handleSearch()"
        >查询
      </el-button>
      <el-button
        size="small"
        type="danger"
        class="handleSearch"
        icon="el-icon-delete"
        @click="empty()"
        >清空</el-button
      >
      <el-button
        icon="el-icon-refresh-left"
        size="small"
        type="primary"
        @click="nosettleaccounts()"
        >转为线下支付</el-button
      >
      <el-button
        size="small"
        type="primary"
        class="handleSearch"
        icon="el-icon-warning-outline"
        @click="sduitpayallinfo()"
        >修改付款账户</el-button
      >
      <el-button
        type="info"
        size="small"
        icon="el-icon-tickets"
        @click="derive()"
        >导出</el-button
      >
      <el-button
        type="warning"
        size="small"
        icon="el-icon-back"
        @click="handleresetPays()"
        >重新支付</el-button
      >
    </div>
    <el-table
      max-height="600"
      :data="tableData"
      border
      style="width: 100%"
      empty-text="暂无数据"
      ref="multipleTable"
      tooltip-effect="dark"
      class="hidden-xs-only"
      @selection-change="handleSelectionChange"
      row-key="id"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        :reserve-selection="true"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="serial_code"
        label="支付单号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="amount"
        label="总金额"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="create_name"
        label="操作人"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="receive_account"
        label="收款账号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="receive_account_name"
        label="收款人姓名"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="receive_bank"
        label="收款银行"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="pay_account"
        label="支付账号"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="created_at"
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="orgarea_name"
        label="地区名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="orgarea_code"
        label="地区编码"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="pay_bank_name"
        label="支付银行"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="fail_detail_reason"
        label="详细原因"
        align="center"
      ></el-table-column>

      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-refresh-left"
            @click="handleDelete(scope)"
            >转为线下支付
          </el-button>
          <!-- <el-button type="warning" size="mini" v-if="
              scope.row.rtnFlg == 'B' ||
              scope.row.rtnFlg == 'D' ||
              scope.row.rtnFlg == 'F' ||
              scope.row.rtnFlg == 'R'
            " icon="el-icon-back" @click="handleresetPay(scope)">重新支付</el-button> -->
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-back"
            @click="handleresetPay(scope)"
            >重新支付</el-button
          >
          <el-button
            size="small"
            type="warning"
            class="handleSearch"
            icon="el-icon-warning-outline"
            @click="sduitpayinfo(scope)"
            >修改付款账户</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      @page="handleSizeChange"
      @pagesize="handleCurrentChange"
      :pageData="pageData"
    ></pagination>
    <eduitestablishDialog
      :eduitestablishDialog="eduitestablishDialog"
      @upData="getData"
    ></eduitestablishDialog>
  </div>
</template>
<script>
import Pagination from "@/components/pagination";
import { getFailList, selectBankList } from "@/api/settlement/bankList";
import {
  getresetPay,
  getresetOnlinePay,
  resetOnlinePayS
} from "@/api/settlement/settlementList";
import { Submenu } from "element-ui";
import { getnowDate } from "@/utils/index";
import { getAreaList } from "@/api/permission/adminlist";
import { getToken } from "@/utils/auth";
import EduitestablishDialog from "@/components/settlement/eduitestablishDialog";
export default {
  components: {
    pagination: Pagination,
    eduitestablishDialog: EduitestablishDialog
  },
  data() {
    return {
      //页面数据
      tableData: [],
      selectedData: [],
      //分页
      pageData: {
        pageSizes: [10, 20],
        pageSize: 10,
        page: 1,
        total: null,
        layout: "total, sizes, prev, pager, next, jumper"
      },
      insideArea: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      },
      eduitestablishDialog: {
        id: "",
        paymentname: "",
        dialogType: "",
        eduitDialogVisible: false
      },
      formData: {},
      search: {
        bank_name: "",
        area: "",
        start_time: "",
        end_time: ""
      },
      date: [],
      //默认时间
      normal_startime: getnowDate().startimer,
      normal_endtime: getnowDate().endtimer
    };
  },
  created() {
    this.search.start_time = this.normal_startime;
    this.search.end_time = this.normal_endtime;
    if (this.normal_startime) {
      this.date.push(this.search.start_time);
    }
    if (this.normal_endtime) {
      this.date.push(this.search.end_time);
    }
    this.getData();
    this.getAreaData();
  },

  methods: {
    //页面数据
    getData() {
      let data = {
        limit: this.pageData.pageSize,
        page: this.pageData.page,
        pay_code: this.search.bank_name,
        orgarea_code: this.search.area,
        start_date: this.search.start_time,
        end_date: this.search.end_time
      };
      getFailList(data)
        .then(res => {
          if (res.code == 0) {
            // res.data.list.data.forEach((res) => {
            //   if (res.rtnFlg == "B") {
            //     res.typeMsg = "退票 银行支付被退票";
            //   } else if (res.rtnFlg == "C") {
            //     res.typeMsg = "撤消 企业撤销";
            //   } else if (res.rtnFlg == "D") {
            //     res.typeMsg = "过期 企业过期不审批";
            //   } else if (res.rtnFlg == "F") {
            //     res.typeMsg = "失败 银行支付失败";
            //   } else if (res.rtnFlg == "U") {
            //     res.typeMsg = "银行挂账";
            //   } else if (res.rtnFlg == "S") {
            //     res.typeMsg = "成功 银行支付成功";
            //   } else if (res.rtnFlg == "R") {
            //     res.typeMsg = "否决 企业审批否决";
            //   } else {
            //     res.typeMsg = " ";
            //   }
            // });
            this.tableData = res.data.list.data;
            this.pageData.page = res.data.list.current_page;
            this.pageData.pagesize = res.data.list.per_page;
            this.pageData.total = res.data.list.total;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index != 2) {
            sums[index] = "";
          } else {
            sums[index] = sums[index].toFixed(4);
          }
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    getAreaData() {
      let data = {
        page: 1,
        limit: 50
      };

      //获取初始化区域列表
      getAreaList(data).then(res => {
        this.insideArea.options = res.data.listdata.map(item => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
      });
    },
    // 搜索区域
    insideRemoteMethods(query) {
      if (query !== "") {
        this.getSupplierLists(query);
      } else {
        this.insideArea.options = [];
      }
    },
    getSupplierLists(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100
      };
      getAreaList(data).then(res => {
        this.insideArea.list = res.data.listdata.map(item => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
        this.insideArea.options = this.insideArea.list.filter(item => {
          this.insideArea.loading = false;
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      });
    },

    // 搜索
    handleSearch() {
      if (this.date.length > 0) {
        this.search.start_time = this.date[0];
        this.search.end_time = this.date[1];
      }
      this.pageData.page = 1;
      this.pageData.total = null;
      this.$refs.multipleTable.clearSelection();
      this.getData();
    },
    //转为线下支付（单选）
    handleDelete(scope) {
      let data = {
        pay_detail_id_str: scope.row.pay_detail_id
      };
      console.log(scope);
      this.$confirm("是否转为线下支付操作?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          getresetPay(data).then(res => {
            if (res.code == 0) {
              this.getData();
              this.$message({
                type: "success",
                message: res.msg || res.message
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消转为线下支付操作"
          });
        });
    },

    //转为线下支付（多选）
    nosettleaccounts() {
      let arrCode = [];
      this.selectedData.forEach(res => {
        arrCode.push(res.pay_detail_id);
      });
      if (this.selectedData.length <= 0) {
        this.$message({
          type: "error",
          message: "请勾选要转为线下支付的列表"
        });
        return;
      }
      this.$confirm("是否将所选转为线下支付?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            pay_detail_id_str: arrCode.join(",")
          };
          getresetPay(data).then(res => {
            if (res.code == 0) {
              this.$refs.multipleTable.clearSelection();
              this.getData();
              this.$message({
                type: "success",
                message: res.msg || res.message
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消转为线下支付修改"
          });
        });
    },

    //重新支付
    handleresetPay(scope) {
      let data = {
        id: scope.row.id,
        bank_type: scope.row.bank_type
      };
      console.log(scope);
      this.$confirm("是否重新支付操作?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          getresetOnlinePay(data).then(res => {
            if (res.code == 0) {
              this.getData();
              this.$message({
                type: "success",
                message: res.msg || res.message
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重新支付操作"
          });
        });
    },
    //重新支付（多选）
    handleresetPays() {
      let arrCode = [];
      this.selectedData.forEach(res => {
        arrCode.push({
          id: res.id,
          bank_type: res.bank_type
        });
      });
      if (this.selectedData.length <= 0) {
        this.$message({
          type: "error",
          message: "请勾选列表"
        });
        return;
      }

      this.$confirm("是否重新支付操作?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            datas: arrCode
          };
          resetOnlinePayS(data).then(res => {
            if (res.code == 0) {
              this.$refs.multipleTable.clearSelection();
              this.getData();
              this.$message({
                type: "success",
                message: res.msg || res.message
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //修改付款银行账号
    sduitpayinfo(scope) {
      this.eduitestablishDialog.id = scope.row.pay_id;
      this.eduitestablishDialog.paymentname = scope.row.payment_id;
      this.eduitestablishDialog.dialogType = "falssend";
      this.eduitestablishDialog.eduitDialogVisible = true;
    },
    //修改付款银行账号(多选)
    sduitpayallinfo() {
      let arrCode = [];
      this.selectedData.forEach(res => {
        arrCode.push(res.pay_id);
      });
      if (this.selectedData.length <= 0) {
        this.$message({
          type: "error",
          message: "请勾选要修改付款银行账号的列表"
        });
        return;
      }
      this.eduitestablishDialog.id = arrCode.join(",");
      // this.eduitestablishDialog.paymentname = scope.row.payment_id;
      this.eduitestablishDialog.paymentname = "";
      this.eduitestablishDialog.dialogType = "falssend";
      this.eduitestablishDialog.eduitDialogVisible = true;
    },
    //清空
    empty() {
      this.getAreaData();
      this.date = [];
      this.date.push(this.normal_startime);
      this.date.push(this.normal_endtime);
      this.search = {
        bank_name: "",
        area: "",
        start_time: this.normal_startime,
        end_time: this.normal_endtime
      };
      this.insideArea = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      };
    },
    //导出
    derive() {
      this.$confirm("是否导出?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          if (this.date.length > 0) {
            this.search.start_time = this.date[0];
            this.search.end_time = this.date[1];
          }
          link.href =
            this.$axios.defaults.baseURL +
            "/api/Onlinepay/exportFailData?token=" +
            getToken() +
            "&pay_code=" +
            this.search.bank_name +
            "&orgarea_code=" +
            this.search.area +
            "&start_date=" +
            this.search.start_time +
            "&end_date=" +
            this.search.end_time;
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出"
          });
        });
    },
    //让勾选操作
    selectable(row, index) {
      if (row.states == "停用" || row.states == "冻结账款") {
        return false;
      } else {
        return true;
      }
    },

    //每页多少条
    handleCurrentChange(val) {
      this.pageData.page = 1;
      this.pageData.pageSize = val;
      this.getData();
    },
    //选取页数
    handleSizeChange(page) {
      this.pageData.page = page;
      this.getData();
    },
    //选取
    handleSelectionChange(val) {
      this.selectedData = val;
    }
  }
};
</script>
<style scoped>
.top {
  position: relative;
}

.add {
  position: absolute;
  right: 0;
  top: 4px;
}

.pagination {
  text-align: right;
  padding: 10px;
}
</style>
